package com.sh.data.engine.domain.common.model.domain;

import com.google.common.collect.Lists;
import com.sh.data.engine.domain.shims.db.model.FieldInfoDomain;
import com.sh.data.engine.domain.shims.db.model.TableInfoDomain;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: mengzheng.mhc
 * @date: 2024/6/19 13:41
 */
@Data
public class SimpleTableFieldDomain {

    private Long tableId;

    private String tableName;

    private String tableComment;

    private List<SimpleFieldInfo> fieldList;

    @Data
    public static class SimpleFieldInfo {

        private String fieldName;

        private String fieldType;

        private String fieldComment;

        private Boolean isPartition;

        private Boolean isPk;
    }

    public SimpleTableFieldDomain() {
    }

    public SimpleTableFieldDomain(TableInfoDomain tableInfo, List<FieldInfoDomain> fieldInfoList) {
        if (tableInfo != null) {
            this.setTableId(tableInfo.getTblId());
            this.setTableName(tableInfo.getTableName());
            this.setTableComment(tableInfo.getTableComment());
        }
        if (!CollectionUtils.isEmpty(fieldInfoList)) {
            List<SimpleFieldInfo> list = Lists.newArrayListWithExpectedSize(fieldInfoList.size());
            for (FieldInfoDomain fieldInfoDomain : fieldInfoList) {
                SimpleFieldInfo simpleFieldInfo = new SimpleFieldInfo();
                simpleFieldInfo.setFieldName(fieldInfoDomain.getFieldName());
                simpleFieldInfo.setFieldType(fieldInfoDomain.getFieldType());
                simpleFieldInfo.setFieldComment(fieldInfoDomain.getComment());
                simpleFieldInfo.setIsPartition(fieldInfoDomain.getIsPartition());
                simpleFieldInfo.setIsPk(fieldInfoDomain.isPk());
                list.add(simpleFieldInfo);
            }
            this.setFieldList(list);
        }
    }

    public List<String> getFieldNameList() {
        if (CollectionUtils.isEmpty(this.getFieldList())) {
            return Collections.emptyList();
        }
        return this.getFieldList().stream()
            .map(SimpleFieldInfo::getFieldName)
            .filter(StringUtils::isNotBlank)
            .distinct()
            .collect(Collectors.toList());
    }
}
